/*
    curlplusplus - a c++ wrapper around libcurl
    Copyright (C) 2012  Francesco "Franc[e]sco" Noferi (francesco1149@gmail.com)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the
    Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
    Boston, MA  02110-1301, USA.
*/

#include "../include/curlplusplus/easy.hpp"

namespace curlpp
{
    // easy methods
    easy::easy() throw(const exception &)
    {
        curl = curl_easy_init();

        if (!curl)
            throw exception("easy: failed to initialize curl");
    }

    easy::easy(const easy &other) throw(const exception &)
    {
        curl = curl_easy_duphandle(other.curl);

        if (!curl)
            throw exception("easy: failed to clone curl handle");
    }

    easy::~easy() throw()
    {
        curl_easy_cleanup(curl);
    }

    void easy::reset() throw()
    {
        curl_easy_reset(curl);
    }

    void easy::pause(int bitmask) throw(const exception &)
    {
        attempt(curl_easy_pause(curl, bitmask), "easy.pause: failed to pause - ");
    }

    void easy::send(void *buffer, size_t buflen, size_t *cb_sent) throw(const exception &)
    {
        attempt(curl_easy_send(curl, buffer, buflen, cb_sent), "easy.recv: failed to send data - ");
    }

    void easy::recv(void *buffer, size_t buflen, size_t *cb_received) throw(const exception &)
    {
        attempt(curl_easy_recv(curl, buffer, buflen, cb_received), "easy.recv: failed to recieve data - ");
    }

    void easy::perform() throw(const exception &)
    {
        attempt(curl_easy_perform(curl), "easy.perform: failed to perform cURL - ");
    }

    char *easy::escape(char *url, int length)
    {
        return curl_easy_escape(curl, url, length);
    }

    char *easy::unescape(char *url, int length, int *outlength)
    {
        return curl_easy_unescape(curl, url, length, outlength);
    }

    void easy::attempt(CURLcode res, std::string errortext) throw(const exception &)
    {
        if (res != CURLE_OK)
            throw exception(errortext + curl_easy_strerror(res));
    }
}
